import { defineStore } from 'pinia'
import { ref, computed, readonly } from 'vue'
import { useAPIService } from '@/services/api'
import type { MCPService, MCPServiceCall } from '@/types'

export const useMCPStore = defineStore('mcp', () => {
  const apiService = useAPIService()

  // 状态
  const services = ref<Map<string, MCPService>>(new Map())
  const serviceCallHistory = ref<Map<string, MCPServiceCall[]>>(new Map()) // serviceId -> calls
  const isLoading = ref<boolean>(false)
  const lastError = ref<string | null>(null)
  const healthCheckResults = ref<Map<string, {
    success: boolean
    responseTime: number
    error?: string
    timestamp: Date
  }>>(new Map())

  // 计算属性
  const allServices = computed(() => {
    return Array.from(services.value.values()).sort((a, b) => a.name.localeCompare(b.name))
  })

  const activeServices = computed(() => {
    return allServices.value.filter(service => service.status === 'active')
  })

  const inactiveServices = computed(() => {
    return allServices.value.filter(service => service.status === 'inactive')
  })

  const errorServices = computed(() => {
    return allServices.value.filter(service => service.status === 'error')
  })

  const serviceCount = computed(() => {
    return {
      total: services.value.size,
      active: activeServices.value.length,
      inactive: inactiveServices.value.length,
      error: errorServices.value.length
    }
  })

  const healthyServices = computed(() => {
    return allServices.value.filter(service => 
      service.healthCheck?.status === 'healthy'
    )
  })

  const unhealthyServices = computed(() => {
    return allServices.value.filter(service => 
      service.healthCheck?.status === 'unhealthy'
    )
  })

  const servicesWithMethods = computed(() => {
    const methodMap = new Map<string, MCPService[]>()
    
    allServices.value.forEach(service => {
      service.methods.forEach(method => {
        if (!methodMap.has(method)) {
          methodMap.set(method, [])
        }
        methodMap.get(method)!.push(service)
      })
    })
    
    return methodMap
  })

  // 服务管理
  const loadServices = async (): Promise<void> => {
    try {
      isLoading.value = true
      lastError.value = null
      
      const serviceList = await apiService.getMCPServices()
      
      // 清空现有服务
      services.value.clear()
      
      // 添加新服务
      serviceList.forEach(service => {
        services.value.set(service.id, service)
      })

    } catch (error) {
      lastError.value = error instanceof Error ? error.message : '加载服务失败'
      throw error
    } finally {
      isLoading.value = false
    }
  }

  const createService = async (serviceData: Omit<MCPService, 'id' | 'createdAt' | 'updatedAt'>): Promise<MCPService> => {
    try {
      isLoading.value = true
      lastError.value = null
      
      const newService = await apiService.createMCPService(serviceData)
      services.value.set(newService.id, newService)
      
      return newService
    } catch (error) {
      lastError.value = error instanceof Error ? error.message : '创建服务失败'
      throw error
    } finally {
      isLoading.value = false
    }
  }

  const updateService = async (serviceId: string, updates: Partial<MCPService>): Promise<MCPService> => {
    try {
      isLoading.value = true
      lastError.value = null
      
      const updatedService = await apiService.updateMCPService(serviceId, updates)
      services.value.set(serviceId, updatedService)
      
      return updatedService
    } catch (error) {
      lastError.value = error instanceof Error ? error.message : '更新服务失败'
      throw error
    } finally {
      isLoading.value = false
    }
  }

  const deleteService = async (serviceId: string): Promise<void> => {
    try {
      isLoading.value = true
      lastError.value = null
      
      await apiService.deleteMCPService(serviceId)
      services.value.delete(serviceId)
      serviceCallHistory.value.delete(serviceId)
      healthCheckResults.value.delete(serviceId)
      
    } catch (error) {
      lastError.value = error instanceof Error ? error.message : '删除服务失败'
      throw error
    } finally {
      isLoading.value = false
    }
  }

  const getService = (serviceId: string): MCPService | null => {
    return services.value.get(serviceId) || null
  }

  const findServicesByMethod = (method: string): MCPService[] => {
    return allServices.value.filter(service => 
      service.methods.includes(method) && service.status === 'active'
    )
  }

  // 健康检查
  const testService = async (serviceId: string): Promise<boolean> => {
    try {
      const result = await apiService.testMCPService(serviceId)
      
      healthCheckResults.value.set(serviceId, {
        success: result.success,
        responseTime: result.responseTime,
        error: result.error,
        timestamp: new Date()
      })

      // 更新服务健康状态
      const service = services.value.get(serviceId)
      if (service) {
        service.healthCheck = {
          lastCheck: new Date(),
          status: result.success ? 'healthy' : 'unhealthy',
          responseTime: result.responseTime
        }
        
        // 如果测试失败，更新服务状态为错误
        if (!result.success && service.status === 'active') {
          service.status = 'error'
        }
      }

      return result.success
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '测试服务失败'
      
      healthCheckResults.value.set(serviceId, {
        success: false,
        responseTime: 0,
        error: errorMessage,
        timestamp: new Date()
      })

      // 更新服务状态为错误
      const service = services.value.get(serviceId)
      if (service) {
        service.status = 'error'
        service.healthCheck = {
          lastCheck: new Date(),
          status: 'unhealthy',
          responseTime: 0
        }
      }

      throw error
    }
  }

  const testAllServices = async (): Promise<{ success: number; failed: number }> => {
    const results = { success: 0, failed: 0 }
    
    const testPromises = activeServices.value.map(async (service) => {
      try {
        const success = await testService(service.id)
        if (success) {
          results.success++
        } else {
          results.failed++
        }
      } catch {
        results.failed++
      }
    })

    await Promise.allSettled(testPromises)
    return results
  }

  const getHealthCheckResult = (serviceId: string) => {
    return healthCheckResults.value.get(serviceId)
  }

  // 服务调用历史
  const addServiceCall = (serviceCall: MCPServiceCall): void => {
    const calls = serviceCallHistory.value.get(serviceCall.serviceId) || []
    calls.push(serviceCall)
    
    // 限制历史记录数量
    if (calls.length > 100) {
      calls.splice(0, calls.length - 100)
    }
    
    serviceCallHistory.value.set(serviceCall.serviceId, calls)
  }

  const getServiceCalls = (serviceId: string): MCPServiceCall[] => {
    return serviceCallHistory.value.get(serviceId) || []
  }

  const clearServiceCalls = (serviceId: string): void => {
    serviceCallHistory.value.delete(serviceId)
  }

  const clearAllServiceCalls = (): void => {
    serviceCallHistory.value.clear()
  }

  // 服务统计
  const getServiceStatistics = (serviceId: string) => {
    const calls = getServiceCalls(serviceId)
    const service = getService(serviceId)
    const healthResult = getHealthCheckResult(serviceId)
    
    if (!service) return null

    return {
      service,
      callCount: calls.length,
      lastCall: calls.length > 0 ? calls[calls.length - 1] : null,
      averageResponseTime: calls.length > 0 
        ? calls.reduce((sum, call) => sum + (call.responseTime || 0), 0) / calls.length 
        : 0,
      healthStatus: healthResult,
      methodsCount: service.methods.length,
      isActive: service.status === 'active'
    }
  }

  const getAllStatistics = () => {
    const stats = {
      totalServices: services.value.size,
      activeServices: activeServices.value.length,
      healthyServices: healthyServices.value.length,
      totalCalls: 0,
      totalMethods: 0,
      averageResponseTime: 0
    }

    let totalResponseTime = 0
    let validCallCount = 0

    allServices.value.forEach(service => {
      stats.totalMethods += service.methods.length
      
      const calls = getServiceCalls(service.id)
      stats.totalCalls += calls.length
      
      calls.forEach(call => {
        if (call.responseTime) {
          totalResponseTime += call.responseTime
          validCallCount++
        }
      })
    })

    if (validCallCount > 0) {
      stats.averageResponseTime = totalResponseTime / validCallCount
    }

    return stats
  }

  // 服务搜索和过滤
  const searchServices = (query: string): MCPService[] => {
    if (!query.trim()) return allServices.value

    const lowerQuery = query.toLowerCase()
    return allServices.value.filter(service =>
      service.name.toLowerCase().includes(lowerQuery) ||
      service.description?.toLowerCase().includes(lowerQuery) ||
      service.endpoint.toLowerCase().includes(lowerQuery) ||
      service.methods.some(method => method.toLowerCase().includes(lowerQuery))
    )
  }

  const filterServicesByStatus = (status: MCPService['status']): MCPService[] => {
    return allServices.value.filter(service => service.status === status)
  }

  const filterServicesByHealth = (isHealthy: boolean): MCPService[] => {
    return allServices.value.filter(service => {
      const healthCheck = service.healthCheck
      if (!healthCheck) return !isHealthy
      return isHealthy ? healthCheck.status === 'healthy' : healthCheck.status === 'unhealthy'
    })
  }

  // 导入导出
  const exportServices = () => {
    return {
      services: allServices.value,
      callHistory: Object.fromEntries(serviceCallHistory.value),
      healthResults: Object.fromEntries(healthCheckResults.value),
      exportedAt: new Date().toISOString(),
      version: '1.0'
    }
  }

  const importServices = async (data: any): Promise<{ success: number; failed: number }> => {
    const results = { success: 0, failed: 0 }
    
    if (!data.services || !Array.isArray(data.services)) {
      throw new Error('Invalid import data format')
    }

    for (const serviceData of data.services) {
      try {
        // 移除ID相关字段，让后端重新生成
        const { id, createdAt, updatedAt, ...cleanServiceData } = serviceData
        await createService(cleanServiceData)
        results.success++
      } catch (error) {
        console.error('Failed to import service:', serviceData.name, error)
        results.failed++
      }
    }

    return results
  }

  // 重置方法
  const resetMCP = (): void => {
    services.value.clear()
    serviceCallHistory.value.clear()
    healthCheckResults.value.clear()
    isLoading.value = false
    lastError.value = null
  }

  return {
    // 状态
    services: readonly(services),
    serviceCallHistory: readonly(serviceCallHistory),
    isLoading: readonly(isLoading),
    lastError: readonly(lastError),
    healthCheckResults: readonly(healthCheckResults),

    // 计算属性
    allServices,
    activeServices,
    inactiveServices,
    errorServices,
    serviceCount,
    healthyServices,
    unhealthyServices,
    servicesWithMethods,

    // 服务管理
    loadServices,
    createService,
    updateService,
    deleteService,
    getService,
    findServicesByMethod,

    // 健康检查
    testService,
    testAllServices,
    getHealthCheckResult,

    // 服务调用历史
    addServiceCall,
    getServiceCalls,
    clearServiceCalls,
    clearAllServiceCalls,

    // 服务统计
    getServiceStatistics,
    getAllStatistics,

    // 搜索和过滤
    searchServices,
    filterServicesByStatus,
    filterServicesByHealth,

    // 导入导出
    exportServices,
    importServices,

    // 重置
    resetMCP
  }
})